const { app, BrowserWindow, Menu, screen, ipcMain } = require("electron");
const initModules = require("./modules");
const path = require("node:path");

let _screenWidth, _screenHeight;

//是否是测试环境
const isDevelopment = !app.isPackaged;

//排除警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";

//解决应用程序冲突
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
}

let window = undefined

//关闭自带菜单
Menu.setApplicationMenu(null);

//开启主窗口：按钮面板，贴边收起
function createMainWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  window = new BrowserWindow({
    titleBarStyle: "hidden",
    width,
    height,
    // alwaysOnTop: true,
    // transparent: true,
    // backgroundColor: "#00000000",
    fullScreen: true,
    icon: path.join(__dirname, 'assets/logo.png'),
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      enableBlinkFeatures: 'SharedArrayBuffer',
    },
  });
  if (isDevelopment) {
    window.loadURL('http://localhost:3321')
    // window.loadURL('https://ris.yuntongjiankang.com')
  } else {
    window.loadFile(path.join(__dirname, "platform/index.html"), {
      hash: "",
    });
  }

  //隐藏任务栏
  // window.setSkipTaskbar(true);
  //是否打开调试工具
  window.webContents.openDevTools()
  window.on('close', () => {
    app.quit()
  })

  ipcMain.on('JUMP-LIST-PAGE', async (event, arg) => {
    window.focus()
  })
}

//程序环境准备好时触发
app.whenReady().then(async () => {
  //获取屏幕宽高
  _screenWidth = screen.getPrimaryDisplay().bounds.width;
  _screenHeight = screen.getPrimaryDisplay().bounds.height;
  //开启loading窗口
  const loadingWindowWidth = 300
  const loadingWindowHeight = 200
  const loadingWindow = new BrowserWindow({
    titleBarStyle: "hidden",
    width: loadingWindowWidth,
    height: loadingWindowHeight,
    alwaysOnTop: true,
    backgroundColor: "#00000000",
    resizable: false,
    transparent: true,
    show: false,
    x: (_screenWidth - loadingWindowWidth) / 2,
    y: (_screenHeight - loadingWindowHeight) / 2 - 90
  });
  loadingWindow.loadFile(path.join(__dirname, "assets/html/loading/index.html"));
  loadingWindow.setSkipTaskbar(true);
  loadingWindow.once("ready-to-show", () => {
    loadingWindow.show();
  });

  await initModules();
  createMainWindow();
  loadingWindow.close()
  //程序被激活，如果目前没有窗口，则创建主窗口
  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createMainWindow();
  });
});

app.on("ready", function () { });

//如果所有的窗口都关闭
app.on("window-all-closed", function () {
  if (process.platform !== "darwin") app.quit();
});

//设置程序ID
// app.setAppUserModelId("雨田PACS");
app.setName("雨田PACS");

//如果是测试环境，开启热部署
if (isDevelopment) {
  try {
    require("electron-reloader")(module);
  } catch (err) { }
}
